package com.globallogic.training.javase.basics;

import java.util.Scanner;

/**
* This program finds and returns two neighbouring numbers
* in an array with the smallest distance to each other.
* @version 1.2 2013-04-05
* @author Ivan Moisiienko
*/

public class NeighbouringNumbers{

	static final String PROMPT_MESSAGE
		= "Enter two or more numbers separated by spaces:";
	static final String RESULT_MESSAGE
		= "The smallest difference starts at index ";

	public static void main(String[] args){

		int[] numbers = provideInput();

		System.out.println(RESULT_MESSAGE
						   + getFirstIndexMinDif(numbers));

	}

	static int[] provideInput() {
		Scanner in = new Scanner(System.in);
		String[] inputTokens;

		do {
			System.out.print(PROMPT_MESSAGE);
			inputTokens = in.nextLine().trim().replaceAll("\\s+", " ").split(" ");
		} while (inputTokens.length < 2);

		int[] numbers = new int[inputTokens.length];
		for (int i = 0; i < numbers.length; i++) {
			numbers[i] = Integer.parseInt(inputTokens[i]);
		}

		return numbers;
	}

	static int getFirstIndexMinDif(int[] numbers) {
		int minDif = Math.abs(numbers[1] - numbers[0]);
		int result = 0;

		for (int i = 2; i < numbers.length; i++) {
			int dif = Math.abs(numbers[i] - numbers[i - 1]);
			if ( dif < minDif ) {
				minDif = dif;
				result = i - 1;
			}
		}
		return result;
	}

}